#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 欢迎信息
echo -e "${GREEN}=== CentOS 7 下 rsync + inotify-tools 实时同步脚本 ===${NC}"
echo -e "${YELLOW}本脚本将自动完成以下操作："
echo -e "1. 实现源目录到目标目录的单向实时同步"
echo -e "2. 使用 inotify-tools 监控文件变动"
echo -e "3. 通过 rsync 进行文件同步"
echo -e "4. 可选更换阿里云YUM源"
echo -e "${BLUE}=============================================${NC}"
echo

# 检查是否为root用户
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}错误：此脚本必须以root用户身份运行${NC}" >&2
    exit 1
fi

# 询问是否更换阿里云YUM源
echo -e "${YELLOW}是否要更换为阿里云YUM源以提高下载速度？${NC}"
read -p "请输入选择 (y/n, 默认n): " change_yum
echo

if [[ $change_yum =~ ^[Yy] ]]; then
    echo -e "${GREEN}正在更换为阿里云YUM源...${NC}"
    # 备份原有源
    yum install -y wget || { echo -e "${RED}安装wget失败${NC}"; exit 1; }
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2>/dev/null
    mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo.backup 2>/dev/null
    
    # 下载阿里云源(适配CentOS 7)
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo || { echo -e "${RED}下载CentOS-Base.repo失败${NC}"; exit 1; }
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo || { echo -e "${RED}下载epel.repo失败${NC}"; exit 1; }
    
    # 清理并生成缓存
    yum clean all && yum makecache
    echo -e "${GREEN}YUM源已更换为阿里云镜像${NC}"
else
    echo -e "${BLUE}跳过YUM源更换${NC}"
fi
echo

# 交互式设置源目录和目标目录
echo -e "${YELLOW}请设置同步目录配置${NC}"
read -p "请输入源目录路径(默认:/var/www/html/public_html/): " SRC
SRC=${SRC:-"/var/www/html/public_html/"}
read -p "请输入目标目录路径(默认:/data/blog_html/): " DST
DST=${DST:-"/data/blog_html/"}
echo

# 确保目录路径以/结尾
[[ "${SRC}" != */ ]] && SRC="${SRC}/"
[[ "${DST}" != */ ]] && DST="${DST}/"

# 创建目录（如果不存在）并检查权限
echo -e "${GREEN}正在检查目录权限...${NC}"
mkdir -p "$SRC" || { echo -e "${RED}无法创建源目录${NC}"; exit 1; }
mkdir -p "$DST" || { echo -e "${RED}无法创建目标目录${NC}"; exit 1; }

# 检查目录是否可写
touch "${SRC}.test_write" 2>/dev/null || { echo -e "${RED}源目录不可写，请检查权限！${NC}"; exit 1; }
rm -f "${SRC}.test_write"
touch "${DST}.test_write" 2>/dev/null || { echo -e "${RED}目标目录不可写，请检查权限！${NC}"; exit 1; }
rm -f "${DST}.test_write"
echo -e "${GREEN}目录权限检查通过${NC}"
echo

# 安装必要软件（强制确认）
echo -e "${GREEN}正在安装 rsync 和 inotify-tools...${NC}"
yum install -y epel-release rsync inotify-tools || { echo -e "${RED}软件安装失败${NC}"; exit 1; }

# 验证 inotifywait 是否安装成功
if ! command -v inotifywait &>/dev/null; then
    echo -e "${RED}错误：inotify-tools 未安装成功，请手动执行 'yum install -y inotify-tools'${NC}"
    exit 1
fi
echo -e "${GREEN}软件安装完成${NC}"
echo

# 创建同步脚本
echo -e "${GREEN}创建同步脚本...${NC}"
cat > /usr/local/bin/sync_files.sh <<EOF
#!/bin/bash
SRC="$SRC"
DST="$DST"
LOG="/var/log/sync_files.log"

# 监控事件并同步
inotifywait -mrq --timefmt '%Y-%m-%d %H:%M' --format '%T %w%f %e' \\
    -e modify,create,delete,move,attrib "\${SRC}" | while read -r file
do
    rsync -avz --delete "\${SRC}" "\${DST}" &>> "\${LOG}"
    echo "[\$(date +'%Y-%m-%d %H:%M:%S')] Synced: \${file}" >> "\${LOG}"
done
EOF

# 设置脚本权限
chmod +x /usr/local/bin/sync_files.sh
echo -e "${GREEN}同步脚本创建完成${NC}"
echo

# 创建systemd服务
echo -e "${GREEN}创建systemd服务...${NC}"
cat > /etc/systemd/system/sync_files.service <<EOF
[Unit]
Description=Real-time sync $SRC to $DST
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/sync_files.sh
Restart=on-failure
User=root

[Install]
WantedBy=multi-user.target
EOF

# 重载systemd并启用服务
systemctl daemon-reload
systemctl start sync_files.service
systemctl enable sync_files.service
echo -e "${GREEN}服务启动完成${NC}"
echo

# 检查服务状态
echo -e "${GREEN}检查服务状态...${NC}"
if systemctl is-active --quiet sync_files.service; then
    echo -e "${GREEN}服务正在运行${NC}"
else
    echo -e "${RED}服务启动失败，请检查日志：${NC}"
    journalctl -u sync_files.service -n 10 --no-pager
    exit 1
fi
echo

# 创建测试文件验证同步
echo -e "${GREEN}验证同步功能...${NC}"
TEST_FILE="testfile_$(date +%s)"
touch "${SRC}${TEST_FILE}"
sleep 2  # 等待同步完成

if [[ -f "${DST}${TEST_FILE}" ]]; then
    echo -e "${GREEN}同步测试成功！${NC}"
    rm -f "${SRC}${TEST_FILE}" "${DST}${TEST_FILE}"
else
    echo -e "${RED}同步测试失败，请检查日志：/var/log/sync_files.log${NC}"
    exit 1
fi
echo

# 完成提示
echo -e "${GREEN}=== 安装完成 ===${NC}"
echo -e "${BLUE}源目录: $SRC"
echo -e "目标目录: $DST"
echo -e "日志文件: /var/log/sync_files.log"
echo -e "管理命令: systemctl [start|stop|restart|status] sync_files.service${NC}"
echo -e "${GREEN}=============================================${NC}"